package com.yunyan.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Date;

public class JwtUtil {

    public static String createToken(String userId) {
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret");
            String token = JWT.create()
                    .withIssuer("auth0")
                    .withClaim("userId", userId)
                    .withExpiresAt(new Date(System.currentTimeMillis() + 3600 * 1000)) // 设置1小时后过期
                    .sign(algorithm);
            return token;
        } catch (Exception exception){
            //Invalid Signing configuration / Couldn't convert Claims.
            return null;
        }
    }

    public static String decodeToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret");
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("auth0")
                    .build(); //Reusable verifier instance
            DecodedJWT jwt = verifier.verify(token);
            return (jwt.getClaim("userId").asString());
        } catch (Exception exception){
            //Invalid signature/claims
            return null;
        }
    }

//    public static void main(String[] args) {
//        String token = createToken("123456");
//        decodeToken(token);
//    }
}
